<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>AI摄影分析</h2>
      <p>上传一张照片，AI将为您分析并生成详细分析和建议</p>
    </div>

    <div class="chat-content">
      <div class="upload-area" v-if="!uploadedImage">
        <div
          class="upload-zone"
          :class="{ 'drag-over': isDragOver }"
          @click="triggerFileInput"
          @dragover.prevent="isDragOver = true"
          @dragleave.prevent="isDragOver = false"
          @drop.prevent="handleDrop"
        >
          <div class="upload-icon">📷</div>
          <p class="upload-text">点击或拖拽上传图片</p>
          <p class="upload-hint">支持 JPG、JPEG、PNG 格式</p>
        </div>

        <input
          ref="fileInput"
          type="file"
          accept=".jpg,.jpeg,.png"
          @change="handleFileSelect"
          style="display: none"
        />
      </div>

      <div class="chat-messages" v-if="uploadedImage">
        <div class="message user-message">
          <div class="message-content">
            <img :src="uploadedImage" alt="上传的图片" class="uploaded-image" />
            <p>请分析这张图片</p>
          </div>
        </div>

        <div class="message ai-message" v-if="aiResponse || isLoading">
          <div class="message-content">
            <div v-if="isLoading && !aiResponse" class="loading">
              <div class="loading-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
              <p>AI正在分析图片...</p>
            </div>

            <MarkdownRenderer
              v-if="aiResponse"
              :content="aiResponse"
            />

            <div v-if="isStreaming" class="streaming-indicator">
              <span class="cursor">|</span>
            </div>
          </div>
        </div>

        <div class="message error-message" v-if="errorMessage">
          <div class="message-content">
            <p>{{ errorMessage }}</p>
          </div>
        </div>
      </div>

      <div class="chat-actions" v-if="uploadedImage">
        <button
          @click="resetChat"
          class="reset-btn"
          :disabled="isLoading || isStreaming"
        >
          {{ (isLoading || isStreaming) ? '处理中...' : '重新上传图片' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onUnmounted } from 'vue'
import { agentApi } from '@/api'
import { uploadByType } from '@/utils/cosUpload'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

export default {
  name: 'Chat',
  components: {
    MarkdownRenderer
  },
  setup() {
    const fileInput = ref(null)
    const uploadedImage = ref('')
    const aiResponse = ref('')
    const isLoading = ref(false)
    const isStreaming = ref(false)
    const errorMessage = ref('')
    const isDragOver = ref(false)
    const eventSource = ref(null)

    const triggerFileInput = () => {
      fileInput.value?.click()
    }

    const handleFileSelect = (event) => {
      const file = event.target.files[0]
      if (file) {
        if (!isValidImageFile(file)) {
          errorMessage.value = '请上传 JPG、JPEG 或 PNG 格式的图片'
          return
        }
        processImage(file)
      }
    }

    const handleDrop = (event) => {
      isDragOver.value = false
      const file = event.dataTransfer.files[0]
      if (file && isValidImageFile(file)) {
        processImage(file)
      }
    }

    const isValidImageFile = (file) => {
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
      return allowedTypes.includes(file.type)
    }

    const processImage = async (file) => {
      if (file.size > 10 * 1024 * 1024) {
        errorMessage.value = '图片大小不能超过10MB'
        return
      }

      try {
        isLoading.value = true
        errorMessage.value = ''

        uploadedImage.value = URL.createObjectURL(file)

        const imageUrl = await uploadByType(file, 'photo')

        const chatKey = await agentApi.chatCreate({ imageUrl })

        await startSSEStream(chatKey)

      } catch (error) {
        console.error('处理图片失败:', error)
        errorMessage.value = error.message || '处理图片失败，请重试'
        isLoading.value = false
      }
    }

    const startSSEStream = async (key) => {
      try {
        isLoading.value = false
        isStreaming.value = true
        aiResponse.value = ''

        const baseURL = import.meta.env.VITE_API_BASE_URL || 'https://www.baddonkey.cn/agentApi'
        const url = `${baseURL}/graph/parallel-stream/expand-translate/v2?key=${key}`

        eventSource.value = new EventSource(url)

        eventSource.value.onmessage = (event) => {
          if (event.data === '[DONE]') {
            eventSource.value?.close()
            eventSource.value = null
            isStreaming.value = false
            return
          }

          try {
            aiResponse.value += event.data
          } catch (error) {
            console.error('解析SSE数据失败:', error)
          }
        }

        eventSource.value.onerror = (error) => {
          console.error('SSE连接错误:', error)
          eventSource.value?.close()
          eventSource.value = null
          isStreaming.value = false

          if (!aiResponse.value) {
            errorMessage.value = 'AI分析失败，请重试'
          }
        }

      } catch (error) {
        console.error('启动SSE流失败:', error)
        isStreaming.value = false
        errorMessage.value = error.message || 'AI分析失败，请重试'
      }
    }

    const resetChat = () => {
      // 关闭现有的SSE连接
      if (eventSource.value) {
        eventSource.value.close()
        eventSource.value = null
      }

      uploadedImage.value = ''
      aiResponse.value = ''
      errorMessage.value = ''
      isLoading.value = false
      isStreaming.value = false

      if (fileInput.value) {
        fileInput.value.value = ''
      }
    }

    // 组件销毁时清理SSE连接
    onUnmounted(() => {
      if (eventSource.value) {
        eventSource.value.close()
        eventSource.value = null
      }
    })

    return {
      fileInput,
      uploadedImage,
      aiResponse,
      isLoading,
      isStreaming,
      errorMessage,
      isDragOver,
      triggerFileInput,
      handleFileSelect,
      handleDrop,
      resetChat,
      isValidImageFile
    }
  }
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  padding: 20px;
  min-height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.chat-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 1200px;
}

.chat-header h2 {
  color: #333;
  margin: 0 0 8px 0;
  font-size: 28px;
}

.chat-header p {
  color: #666;
  margin: 0;
  font-size: 16px;
}

.chat-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 100%;
  max-width: 1200px;
}

.upload-area {
  padding: 40px;
}

.upload-zone {
  border: 2px dashed #ddd;
  border-radius: 12px;
  padding: 60px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.upload-zone:hover,
.upload-zone.drag-over {
  border-color: #007bff;
  background: #f0f8ff;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 18px;
  color: #333;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.upload-hint {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.chat-messages {
  padding: 40px;
  min-height: 500px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.message {
  display: flex;
  width: 100%;
}

.user-message {
  justify-content: flex-end;
}

.ai-message,
.error-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 60%;
  padding: 20px 24px;
  border-radius: 18px;
  position: relative;
  font-size: 15px;
  line-height: 1.6;
    text-align: left;
}

.user-message .message-content {
  background: #007bff;
  color: white;
}

.ai-message .message-content {
  background: #f1f3f4;
  color: #333;
}

.error-message .message-content {
  background: #fee;
  color: #e74c3c;
  border: 1px solid #fcc;
}

.uploaded-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  margin-bottom: 10px;
  display: block;
}

.loading {
  display: flex;
  align-items: center;
  gap: 12px;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #007bff;
  animation: loading 1.4s ease-in-out infinite both;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.streaming-indicator {
  display: inline-block;
  margin-left: 4px;
}

.cursor {
  animation: blink 1s infinite;
  font-weight: bold;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.chat-actions {
  padding: 20px;
  border-top: 1px solid #eee;
  text-align: center;
}

.reset-btn {
  padding: 10px 24px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.reset-btn:hover {
  background: #5a6268;
}

@media (max-width: 768px) {
  .chat-container {
    padding: 10px;
  }

  .chat-header {
    padding: 30px 20px;
    margin-bottom: 20px;
  }

  .chat-header h2 {
    font-size: 24px;
  }

  .chat-messages {
    padding: 20px;
    min-height: 300px;
    gap: 16px;
  }

  .message-content {
    max-width: 85%;
    padding: 16px 20px;
    font-size: 14px;
  }

  .upload-area {
    padding: 20px;
  }

  .upload-zone {
    padding: 40px 20px;
  }

  .uploaded-image {
    max-width: 150px;
    max-height: 150px;
  }
}
</style>